package com.audaque.springboot.foshanupload.web.config;

import com.audaque.springboot.foshanupload.web.introspector.ObjectMapperAnnoIntrospector;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 服务端和客户端都需要对jackson处理：方式1，在用到ObjectMapper来定义json转换器的时候更新ObjectMapper
 */


@Configuration
public class JacksonRegistrationConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;


    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
        //新建
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        //加工
        AnnotationIntrospector ai = objectMapper.getSerializationConfig().getAnnotationIntrospector();
        //注册自定义内省器（只能加一个，后边加的会覆盖前边的）
        AnnotationIntrospector newAi = AnnotationIntrospectorPair.pair(ai, new ObjectMapperAnnoIntrospector());
        //注册注解拦截器
        //setAnnotationIntrospector:同时设置序列化和反序列化
        //setAnnotationIntrospectosr:分开设置序列化和反序列化
        objectMapper.setAnnotationIntrospector(newAi);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        return jackson2HttpMessageConverter;
    }


    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        //注册
        int size = converters.size();
        converters.add(size, mappingJackson2HttpMessageConverter);
    }
}
